import re

from django.contrib.auth.backends import ModelBackend

from apps.users.models import User


def get_user_by_account(account):
    try:
        if re.match(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+',account):
            user=User.objects.get(email=account)
        else:
            user=User.objects.get(username=account)
    except Exception as e:
        print(e)
        return None
    else:

        return user
class UsernameEmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        '''
        重写认证方法
        :param request:
        :param username: 用户名或者邮箱
        :param password: 密码明文
        :param kwargs:
        :return: user
        '''
        user=get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None